package com.sunsharing.wsdlcall;

import com.sunsharing.common.Context;
import com.sunsharing.common.ContextCreate;
import com.sunsharing.common.FlowMsg;
import com.sunsharing.common.config.Config;
import com.sunsharing.common.config.ServiceModel;
import com.sunsharing.common.utils.StringUtils;
import com.sunsharing.dispatch.Dispatch;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * User: criss
 * Date: 13-4-12
 * Time: 上午12:00
 * To change this template use File | Settings | File Templates.
 */
public class Request {

    /**默认的运行策略*/
    static ExecutorService defaultExecutorService = Executors.newFixedThreadPool(100);

    static Map<String,ExecutorService> serviceExcutor = new HashMap<String, ExecutorService>();

    static Lock lock =  new ReentrantLock();

    static Logger logger = Logger.getLogger(Request.class);
    public static void request(Context context) {

        ServiceModel serviceMode =
                Config.getInstance().getServiceModelByName(context.getMsg().serviceId);
        ExecutorService myExcutor = null;
        if(StringUtils.isBlank(serviceMode.limit))
        {
            myExcutor = defaultExecutorService;
        }else
        {
            lock.lock();
            try
            {
                if(serviceExcutor.get(serviceMode.name)==null)
                {
                    serviceExcutor.put(serviceMode.name,Executors.newFixedThreadPool(new Integer(serviceMode.limit)));
                }
            }catch (Exception e)
            {
                logger.error("初始化服务线程失败",e);
                throw new RuntimeException("初始化服务线程失败");
            }finally {
                lock.unlock();
            }
            myExcutor = serviceExcutor.get(serviceMode.name);
        }

        CallServiceThread t = new CallServiceThread(context);
        myExcutor.execute(t);


    }
}

class CallServiceThread implements Runnable
{
    Context reqContext;
    public CallServiceThread(Context reqContext)
    {
        this.reqContext = reqContext;
    }
    public void run()
    {
        String result = "服务返回结果";

//        if(reqContext.getMsg() instanceof FlowMsg)
//        {
//
//            ((FlowMsg)reqContext.getMsg()).leaveCurrentNode(result);
//        }else
//        {
//            Context restContext = ContextCreate.createResultContext(result, reqContext);
//            new Dispatch().run(restContext);
//        }
//        Context restContext = ContextCreate.createResultContext(result, reqContext);

        reqContext.getMsg().serviceId = "";

        //TODO 错误异常处理


        ((FlowMsg)reqContext.getMsg()).leaveCurrentNode(result);
    }
}
